package com.company.indicationshots.activity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.company.indicationshots.R;
import com.company.indicationshots.database.DatabaseHelper;
import com.company.indicationshots.util.EditLoseFocus;
import com.company.indicationshots.util.EditTextClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
//用户设置页面
public class UserSettingActivity extends AppCompatActivity {

    List<Map<String, String>> selectUserData = new ArrayList<>();
    SimpleAdapter selectUserAdapter = null;

    @SuppressLint({"Range", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_setting);


        ImageView userClose = findViewById(R.id.userClose);
        userClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserSettingActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        //为标签设置点击变背景颜色
        TextView commSet = findViewById(R.id.commSet);
        TextView funcSet = findViewById(R.id.funcSet);

        commSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserSettingActivity.this, CommSettingActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0); // 0表示没有动画
            }
        });

        funcSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserSettingActivity.this, FuncSettingActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0); // 0表示没有动画
            }
        });

        //点击输入框获得焦点并弹出软键盘
        EditText userNameView = findViewById(R.id.userName);
        EditText numberView = findViewById(R.id.number);

        EditTextClick.setEditTextClickListener(userNameView, this);
        EditTextClick.setEditTextClickListener(numberView, this);

        DatabaseHelper dbHelper = new DatabaseHelper(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        //创建适配器给已添加用户列表装配数据
        ListView addUserList = findViewById(R.id.addUserList);

        List<Map<String, String>> addUserData = new ArrayList<>();
        Map<String, String> map = null;

        String sql = "select id,name,number from user where isSelect = 0";
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            int addUserId = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String number = cursor.getString(cursor.getColumnIndex("number"));
            map = new HashMap<>();
            map.put("addUserId", String.valueOf(addUserId));
            map.put("addUserName", name);
            map.put("addUserNumber", number);
            addUserData.add(map);
        }
        cursor.close();
        db.close();

        db = dbHelper.getWritableDatabase();
        sql = "select id,name,number from user where isSelect = 1";
        cursor = db.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String number = cursor.getString(cursor.getColumnIndex("number"));
            map = new HashMap<>();
            map.put("selectUserId", String.valueOf(id));
            map.put("selectUserName", name);
            map.put("selectUserNumber", number);
            selectUserData.add(map);
        }
        cursor.close();
        db.close();


        String[] from = {"addUserId","addUserName", "addUserNumber"};
        int[] to = {R.id.addUserId,R.id.addUserName, R.id.addUserNumber};

        //加载已添加用户数据
        SimpleAdapter addUserAdapter = new SimpleAdapter(this, addUserData, R.layout.setting_add_user_item, from, to) {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView delete = view.findViewById(R.id.delete);
                TextView join = view.findViewById(R.id.join);

                delete.setOnClickListener(new View.OnClickListener() {
                    SQLiteDatabase db = dbHelper.getWritableDatabase();

                    @Override
                    public void onClick(View v) {
                        Map<String, String> map = (Map<String, String>) getItem(position);
                        String number = map.get("addUserNumber");
                        String sql = "delete from user where number = ?";
                        db.execSQL(sql, new String[]{number});
                        db.close();

                        addUserData.remove(position);
                        notifyDataSetChanged();
                    }
                });

                String sql = "update user set isSelect = 1 where id = ?";
                join.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(CollUtil.isEmpty(selectUserData)) {
                            Map<String, String> map = (Map<String, String>) getItem(position);
                            String selectUserId = map.get("addUserId");
                            String selectUserName = map.get("addUserName");
                            String selectUserNumber = map.get("addUserNumber");
                            map = new HashMap<>();
                            map.put("selectUserId",selectUserId);
                            map.put("selectUserName", selectUserName);
                            map.put("selectUserNumber", selectUserNumber);
                            setData(map);

                            addUserData.remove(position);
                            notifyDataSetChanged();

                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                            db.execSQL(sql,new String[]{selectUserId});
                            db.close();
                        }
                    }
                });
                return view;
            }
        };

        addUserList.setAdapter(addUserAdapter);

        ListView selectUserList = findViewById(R.id.selectUserList);

        from = new String[]{"selectUserId","selectUserName", "selectUserNumber"};
        to = new int[]{R.id.selectUserId,R.id.selectUserName, R.id.selectUserNumber};

        //加载已选择用户数据
        selectUserAdapter = new SimpleAdapter(this, selectUserData, R.layout.setting_select_user_item, from, to) {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                ImageView top = view.findViewById(R.id.top);
                ImageView up = view.findViewById(R.id.up);
                ImageView down = view.findViewById(R.id.down);
                ImageView bottom = view.findViewById(R.id.bottom);
                TextView remove = view.findViewById(R.id.remove);
                Map<String, String> map = (Map<String, String>) getItem(position);

                top.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (position != 0) {
                            selectUserData.remove(position);
                            selectUserData.add(0, map);
                            notifyDataSetChanged();
                        }
                    }
                });

                up.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (position != 0){
                            selectUserData.remove(position);
                            selectUserData.add(position - 1, map);
                            notifyDataSetChanged();
                        }
                    }
                });

                down.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (position != selectUserData.size() - 1){
                            selectUserData.remove(position);
                            selectUserData.add(position + 1, map);
                            notifyDataSetChanged();
                        }
                    }
                });

                bottom.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (position != selectUserData.size() - 1) {
                            selectUserData.remove(position);
                            selectUserData.add(map);
                            notifyDataSetChanged();
                        }
                    }
                });

                String sql = "update user set isSelect = 0 where id = ?";
                remove.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Map<String, String> map = (Map<String, String>) getItem(position);
                        String addUserId = map.get("selectUserId");
                        String addUserName = map.get("selectUserName");
                        String addUserNumber = map.get("selectUserNumber");
                        map = new HashMap<>();
                        map.put("addUserId",addUserId);
                        map.put("addUserName", addUserName);
                        map.put("addUserNumber", addUserNumber);
                        addUserData.add(map);
                        addUserAdapter.notifyDataSetChanged();

                        selectUserData.remove(position);
                        notifyDataSetChanged();
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        db.execSQL(sql,new String[]{addUserId});
                        db.close();
                    }
                });
                return view;
            }
        };

        selectUserList.setAdapter(selectUserAdapter);

        TextView addUser = findViewById(R.id.addUser);
        TextView message = findViewById(R.id.message);
        String createTime = DateUtil.format(DateUtil.date(), "yyyy/MM/dd HH:mm");
        //添加用户点击事件
        addUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = userNameView.getText().toString();
                String number = numberView.getText().toString();

                if (TextUtils.isEmpty(userName)) {
                    message.setText("用户名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(number) || number.length() < 4) {
                    message.setText("编号至少四位字符");
                    return;
                }

                SQLiteDatabase db = dbHelper.getWritableDatabase();
                String sql = "select number from user where number = ?";
                Cursor cursor = db.rawQuery(sql, new String[]{number});
                if (cursor.moveToFirst()) {
                    message.setText("编号必须唯一");
                    return;
                }

                message.setText("");

                //把新添加的用户保存在数据库
                ContentValues values = new ContentValues();
                values.put("name", userName);
                values.put("number", number);
                values.put("isSelect",0);
                values.put("create_time", createTime);
                db.insert("user", null, values);

                sql = "select last_insert_rowid() AS id from user";

                cursor = db.rawQuery(sql, null);
                int id = 0;
                if (cursor.moveToFirst()){
                     id =  cursor.getInt(cursor.getColumnIndex("id"));
                }

                Map<String, String> map = new HashMap<>();
                map.put("addUserId", String.valueOf(id));
                map.put("addUserName", userName);
                map.put("addUserNumber", number);
                addUserData.add(map);
                addUserAdapter.notifyDataSetChanged();

                cursor.close();
                db.close();

                //使EditText失去焦点
                userNameView.clearFocus();
                numberView.clearFocus();
                // 获取InputMethodManager实例
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 关闭软键盘
                imm.hideSoftInputFromWindow(userNameView.getWindowToken(), 0);
            }
        });

        TextView confirm = findViewById(R.id.confirm);

        //确认选择点击事件
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String shooter;
                String shooterText;
                if (CollUtil.isEmpty(selectUserData)) {
                    shooter = "未指定";
                } else {
                    Map<String, String> map = selectUserData.get(0);
                    shooter = map.get("selectUserName");
                }
                if (shooter.length() < 4) {
                    shooterText = "射手 : " + shooter;
                } else {
                    shooterText = "射手:" + shooter;
                }
                Intent intent = new Intent(UserSettingActivity.this, MainActivity.class);
                intent.putExtra("shooterText", shooterText);
                intent.putExtra("activity", "userSetting");
                startActivity(intent);
            }
        });

        ConstraintLayout layout = findViewById(R.id.userSetLayout);

        EditLoseFocus.loseFocus(layout,this,userNameView);
        EditLoseFocus.loseFocus(layout,this,numberView);

    }

    //已选用户UI刷新
    public void setData(Map<String, String> map) {
        selectUserData.add(map);
        selectUserAdapter.notifyDataSetChanged();
    }

}